﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;

namespace Veralkohol.Commons
{
    public class LocalPersistence : IDiagramPersistence
    {

        public void Save(PersistentDiagram data)
        {
            SaveFileDialog sdlg = new SaveFileDialog();
            sdlg.DefaultExt = ".axml";
            sdlg.Filter = "Alcoholic XML documents (.axml)|*.axml";
            bool? result2 = sdlg.ShowDialog();
            if (result2 == true)
            {
                string filename = sdlg.FileName;



                XmlSerializer xsSubmit = new XmlSerializer(typeof(PersistentDiagram));
                TextWriter sww = new StreamWriter(filename);
                XmlWriter writer = XmlWriter.Create(sww);
                try
                {
                    xsSubmit.Serialize(writer, data);
                    string messageBoxText = "A mentés sikerült! :)                              ";
                    string caption = "Mentés :)";
                    MessageBoxButton button = MessageBoxButton.OK;
                    MessageBoxImage icon = MessageBoxImage.Information;
                    MessageBox.Show(messageBoxText, caption, button, icon);
                }
                catch
                {
                    string messageBoxText = "A mentés nem sikerült! :(                          ";
                    string caption = "Mentés :(";
                    MessageBoxButton button = MessageBoxButton.OK;
                    MessageBoxImage icon = MessageBoxImage.Error;
                    MessageBox.Show(messageBoxText, caption, button, icon);
                }
                sww.Close();
            }
        }

        public PersistentDiagram Load()
        {
            OpenFileDialog odlg = new OpenFileDialog();
            odlg.DefaultExt = ".axml";
            odlg.Filter = "Alcoholic XML documents (.axml)|*.axml";
            bool? result2 = odlg.ShowDialog();
            if (result2 == true)
            {
                string filename = odlg.FileName;
                XmlSerializer ser = new XmlSerializer(typeof(PersistentDiagram));
                using (XmlReader reader = XmlReader.Create(filename))
                {
                    return (PersistentDiagram)ser.Deserialize(reader);
                }
            }
            else return null;
        }
    }
}
